package com.meida.base.provider.service;

import com.meida.common.enums.StateEnum;
import com.meida.common.utils.ApiAssert;
import com.meida.module.admin.client.constants.BaseConstants;
import com.meida.module.admin.client.model.UserAccount;
import com.meida.module.admin.provider.service.BaseUserAccountService;
import com.meida.common.oauth2.OpenOAuth2ClientProperties;
import com.meida.common.security.OpenUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * Security用户信息获取实现类
 *
 * @author zyf
 */
@Slf4j
@Service("userDetailService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private BaseUserAccountService baseUserAccountService;
    @Autowired
    private OpenOAuth2ClientProperties clientProperties;
    /**
     * 认证中心名称
     */
    @Value("${spring.application.name}")
    private String AUTH_SERVICE_ID;

    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        UserAccount account = baseUserAccountService.login(username);
        if (account == null || account.getAccountId() == null) {
            throw new UsernameNotFoundException("系统用户 " + username + " 不存在!");
        }
        if (StateEnum.DISABLE.getCode().equals(account.getStatus())) {
            ApiAssert.failure("账户已禁用");
        }
        Integer status = account.getUserProfile().getStatus();
        if (StateEnum.DISABLE.getCode().equals(status)) {
            ApiAssert.failure("用户已禁用");
        }
        boolean accountNonLocked = account.getUserProfile().getStatus().intValue() != BaseConstants.USER_STATE_LOCKED;
        boolean credentialsNonExpired = true;
        boolean enable = account.getUserProfile().getStatus().intValue() == BaseConstants.USER_STATE_NORMAL ? true : false;
        boolean accountNonExpired = true;
        String clientId = clientProperties.getOauth2().get("admin").getClientId();
        return new OpenUser(clientId, account.getDomain(), account.getUserId(), account.getAccount(), account.getPassword(), account.getUserProfile().getAuthorities(), accountNonLocked, accountNonExpired, enable, credentialsNonExpired, account.getUserProfile().getNickName(), account.getUserProfile().getAvatar());
    }
}
